/**
 * @description  银行间质押券信息(新增&编辑)（回购指令）
 * @author shenhong
 */
import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { message, Row, Col, Select } from 'antd';
import { SecuritiesCodeC, InputNumberC, codeType, TradeHoldC } from '../../../../comps';
import _ from 'lodash';

const FormItem = Form.Item;
const FormItemLayout = {
  labelCol: {
    xs: { span: 4, offset: 0 },
    sm: { span: 9, offset: 0 },
    md: { span: 9, offset: 0 },
    lg: { span: 9, offset: 0 },
    xl: { span: 8, offset: 0 },
    xxl: { span: 6, offset: 0 },
  },
  wrapperCol: {
    xs: { span: 18, offset: 0 },
    sm: { span: 14, offset: 0 },
    md: { span: 14, offset: 0 },
    lg: { span: 14, offset: 0 },
    xl: { span: 14, offset: 0 },
    xxl: { span: 17, offset: 0 },
  },
};
@Form.create()
class AddBond extends PureComponent {
  constructor() {
    super();
    this.state = {
      info: undefined, // 证券组件抛出的信息
      sybj: 0, // 融资回购时计算出的票面金额
      info2: undefined, // 融资回购时质押券选择框抛出信息
      isChange: false, // 标记质押券是否改变
    };
  }
  componentDidMount() {
    this.props.onRef(this);
    const { record, isEdit, positionArr, direct } = this.props;
    if (isEdit && direct == '2') {
      if (positionArr && positionArr.length) {
        positionArr.map((item) => {
          //  若exchangecode与tradingcode不等于改变后的值
          if (record !== undefined && item.pledgeBondCode == record.tradingcode && item.secuabbr == record.pledgeBondName) {
            obj = item;
          }
        });
        const num = obj.totalValue / Number(obj.t0Number); // 票面金额=剩余票面总额/T+0可用数量
        this.setState({
          info2: obj,
          sybj: num,
        });
      }
    } else if (isEdit && direct == '1') {
      this.securities.getSecuritiesList(record.exchangeCode + '-' + record.tradingcode, undefined, true);
    }
    let obj = {};
  }

  // 将modal框的表单值抛出
  getData = () => {
    const {
      form: { validateFields },
      direct,
    } = this.props;
    const { info2 } = this.state;
    let query = {};
    validateFields((err, fieldsValue) => {
      if (!err) {
        query = _.cloneDeep(fieldsValue);
        query.info = this.state.info; // 委托方向为融资回购时，质押券数量不大于T+0可用数量
        if (direct == '2' && query.pledgeAmount > info2.t0Number) {
          message.warning('质押券数量不可大于T+0可用数量');
          query = undefined; // 大于T+0可用数量时抛出信息为undefined
        }
        query.info2 = this.state.info2;
      } else {
        query = undefined;
      }
    });
    return query;
  };

  // 质押券改变事件（融券回购）
  handleChange = (e) => {
    const {
      form: { setFieldsValue },
      isEdit,
      record,
    } = this.props;
    if (e) {
      this.setState({
        info: e, // 证券组件抛出的信息存入state管理
      });
      if (isEdit) {
        setFieldsValue({
          pledgeAmount: record.pledgeAmount,
          pledgeRatio: record.pledgeRatio,
        });
      } else {
        setFieldsValue({
          pledgeAmount: undefined,
          pledgeRatio: undefined,
        });
      }
    }
  };

  // 质押券数量改变事件
  handleChangeNum = (e) => {
    const { info } = this.state;
    const {
      direct,
      form: { setFieldsValue },
    } = this.props;
    if (e && e !== undefined) {
      if (direct == '1') {
        if (!info) return;
        const num = info.sybj * e;
        setFieldsValue({
          valuationPrice: num, // 融券回购时自动回填的券面金额（债券券面金额=质押券数量*票面金额）
          pledgeRatio: undefined, // 质押券数量改变清空折扣率与成交金额
          denomination: undefined,
        });
      } else if (direct == '2') {
        const num = this.state.sybj * e;
        setFieldsValue({
          valuationPrice: num, // 融资回购时自动回填的券面金额（债券券面金额=质押券数量*票面金额）
          pledgeRatio: undefined, // 质押券数量改变清空折扣率与成交金额
          denomination: undefined,
        });
      }
    }
  };

  // 折扣率改变事件
  handleChangeRate = (e) => {
    const { info } = this.state;
    const {
      direct,
      form: { setFieldsValue, getFieldValue },
    } = this.props;
    if (e && e !== undefined) {
      const num = (getFieldValue('valuationPrice') * e) / 100;
      setFieldsValue({
        denomination: num, // 融券&&融券回购时自动回填的成交金额（折扣率*券面金额）
      });
    }
  };

  // 融资回购时质押券改变获取票面金额
  handleChange1 = (e) => {
    const {
      form: { setFieldsValue },
      positionArr,
    } = this.props;
    if (e) {
      let data = {};
      positionArr.map((item) => {
        if (item.pledgeBondCode + '-' + item.pledgeBondName == e) {
          data = item;
        }
      });
      const num = data.totalValue / Number(data.t0Number); // 票面金额=剩余票面总额/T+0可用数量
      setFieldsValue({
        pledgeAmount: undefined,
        pledgeRatio: undefined,
      });
      this.setState({
        sybj: num,
        info2: data,
      });
    }
  };
  // 展示持仓组件
  showTradeHold = () => {
    const { direct, portfolio, productGroupId, type } = this.props;
    const { info2 } = this.state;
    return (
      <div>
        {direct == '2' ? (
          <div style={{ marginBottom: '15px' }}>
            <TradeHoldC
              portfolio={portfolio}
              productGroupId={productGroupId}
              type={type}
              tradingcode={info2 ? info2.pledgeBondCode : ''}
              exchangecode={info2 ? info2.exchangeCode : ''}
              hasHeader={false}
            />
          </div>
        ) : (
          ''
        )}
      </div>
    );
  };
  // 展示质押券表格以及新增按钮
  showContent = () => {
    // zgPledgeVo 为编辑或详细或下达时的回填信息
    const {
      form: { getFieldDecorator },
      record,
      direct,
      positionArr,
      isEdit,
    } = this.props;
    return (
      // direct =1-融券回购,2-融资回购
      <Form>
        <Row>
          {direct == '2' ? (
            <Col span={12}>
              <FormItem label={'质押券'} {...FormItemLayout}>
                {getFieldDecorator('tradingcode', {
                  initialValue: isEdit ? record.tradingcode + '-' + record.secuabbr : '',
                  rules: [{ required: true, message: `请选择质押券` }],
                })(
                  <Select
                    onChange={this.handleChange1}
                    placeholder='请选择'
                    filterOption={(
                      input,
                      option, //模糊搜索value 和 title
                    ) => {
                      return option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0 || option.props.value.toLowerCase().indexOf(input.toLowerCase()) >= 0;
                    }}
                    showSearch
                  >
                    {positionArr && positionArr.length
                      ? positionArr.map((item) => {
                          return (
                            <Select.Option
                              // key={ item.pledgeBondCode}
                              value={item.pledgeBondCode + '-' + item.pledgeBondName}
                            >{`${item.pledgeBondCode}-${item.pledgeBondName}`}</Select.Option>
                          );
                        })
                      : null}
                  </Select>,
                )}
              </FormItem>
            </Col>
          ) : (
            <Col span={12}>
              <SecuritiesCodeC
                title='质押券'
                form={this.props.form}
                initialValue={isEdit ? record.exchangeCode + '-' + record.tradingcode : ''}
                dataIndex='tradingcode'
                codeType={codeType.zq}
                queryItems={{ exchangeCode: '113', clientCode: this.props.trustee }}
                onChange={(e) => this.handleChange(e)}
                extraLayout={FormItemLayout}
                onRef={(ref) => (this.securities = ref)}
                rules={[{ required: true, message: '请选择代码!' }]}
              />
            </Col>
          )}
          <Col span={12}>
            <InputNumberC
              title='质押券数量'
              dataIndex='pledgeAmount'
              placeholder='请输入'
              rules={[{ required: true, message: `请输入质押券数量` }]}
              initialValue={isEdit ? record.pledgeAmount : ''}
              form={this.props.form}
              onChange={(e) => this.handleChangeNum(e)}
              formItemLayout={FormItemLayout}
              min={1}
              precision={0}
              unit='张'
            />
          </Col>
        </Row>
        <Row>
          <Col span={12}>
            <InputNumberC
              title='折算率'
              dataIndex='pledgeRatio'
              placeholder='请输入'
              rules={[
                { required: true, message: `请输入折算率` },
                { pattern: /^(?!(0[0-9]{0,}$))[0-9]{1,}[.]{0,}[0-9]{0,}$/, message: '折算率须大于0' },
              ]}
              precision={2}
              min={0}
              max={100}
              initialValue={isEdit ? record.pledgeRatio : ''}
              form={this.props.form}
              onChange={(e) => this.handleChangeRate(e)}
              formItemLayout={FormItemLayout}
              unit='%'
            />
          </Col>
          <Col span={12}>
            <InputNumberC
              title='债券券面金额：'
              dataIndex='valuationPrice'
              placeholder='请输入'
              precision={2}
              initialValue={isEdit ? record.valuationPrice : ''}
              fsplitStyle={true}
              form={this.props.form}
              formItemLayout={FormItemLayout}
              disabled={true}
              unit='元'
            />
          </Col>
        </Row>
        <Row>
          <Col span={12}>
            <InputNumberC
              title='成交金额'
              dataIndex='denomination'
              placeholder='请输入'
              // rules={[{ required: true, message: `请输入成交金额` }]}
              precision={2}
              initialValue={isEdit ? record.denomination : ''}
              splitStyle={true}
              form={this.props.form}
              formItemLayout={FormItemLayout}
              disabled={true}
              unit='元'
            />
          </Col>
        </Row>
      </Form>
    );
  };

  render() {
    return (
      <div>
        {this.showTradeHold()}
        {this.showContent()}
      </div>
    );
  }
}
export default connect(({ interBankBasicInfoM }) => ({
  interBankBasicInfoM,
}))(AddBond);
